<template>
  <div class="menu-permission-binding">
    <div class="binding-header">
      <h3>菜单权限绑定状态</h3>
      <div class="header-actions">
        <el-button type="info" @click="checkMapping" :loading="checkLoading">
          检查映射
        </el-button>
        <el-button type="warning" @click="fixMapping" :loading="fixLoading">
          修复映射
        </el-button>
        <el-button type="primary" @click="initMapping" :loading="initLoading">
          初始化映射
        </el-button>
      </div>
    </div>

    <div class="binding-content" v-loading="loading">
      <el-alert
        v-if="mappingStatus"
        :title="mappingStatus.title"
        :type="mappingStatus.type"
        :description="mappingStatus.description"
        show-icon
        :closable="false"
        style="margin-bottom: 20px;"
      />

      <div class="statistics-grid" v-if="statistics">
        <div class="stat-card">
          <div class="stat-value">{{ statistics.totalMenus }}</div>
          <div class="stat-label">总菜单数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ statistics.totalPermissions }}</div>
          <div class="stat-label">总权限数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ statistics.mappedMenus }}</div>
          <div class="stat-label">已映射菜单</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ statistics.unmappedMenus }}</div>
          <div class="stat-label">未映射菜单</div>
        </div>
      </div>

      <div class="mapping-details" v-if="mappingDetails">
        <h4>映射详情</h4>
        <el-table :data="mappingDetails" stripe border>
          <el-table-column prop="menuName" label="菜单名称" />
          <el-table-column prop="menuCode" label="菜单编码" />
          <el-table-column prop="menuType" label="菜单类型">
            <template #default="{ row }">
              <el-tag :type="getMenuTypeTag(row.menuType)" size="small">
                {{ getMenuTypeText(row.menuType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="permissionCodes" label="关联权限">
            <template #default="{ row }">
              <div v-if="row.permissionCodes && row.permissionCodes.length > 0">
                <el-tag 
                  v-for="code in row.permissionCodes" 
                  :key="code" 
                  size="small" 
                  style="margin: 2px;"
                >
                  {{ code }}
                </el-tag>
              </div>
              <el-text v-else type="warning">无关联权限</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="绑定状态">
            <template #default="{ row }">
              <el-tag 
                :type="row.permissionCodes && row.permissionCodes.length > 0 ? 'success' : 'danger'" 
                size="small"
              >
                {{ row.permissionCodes && row.permissionCodes.length > 0 ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const loading = ref(false)
const checkLoading = ref(false)
const fixLoading = ref(false)
const initLoading = ref(false)

const mappingStatus = ref(null)
const statistics = ref(null)
const mappingDetails = ref([])

// 检查菜单权限映射
const checkMapping = async () => {
  try {
    checkLoading.value = true
    const response = await request.get('/menu-permission-mapping/check')
    
    if (response.success) {
      ElMessage.success('检查完成')
      parseMappingResult(response.data)
    } else {
      ElMessage.error(response.message || '检查失败')
    }
  } catch (error) {
    console.error('检查菜单权限映射失败:', error)
    ElMessage.error('检查失败')
  } finally {
    checkLoading.value = false
  }
}

// 修复菜单权限映射
const fixMapping = async () => {
  try {
    fixLoading.value = true
    const response = await request.post('/menu-permission-mapping/fix')
    
    if (response.success) {
      ElMessage.success('修复完成')
      parseMappingResult(response.data)
      // 修复后重新检查
      await checkMapping()
    } else {
      ElMessage.error(response.message || '修复失败')
    }
  } catch (error) {
    console.error('修复菜单权限映射失败:', error)
    ElMessage.error('修复失败')
  } finally {
    fixLoading.value = false
  }
}

// 初始化菜单权限映射
const initMapping = async () => {
  try {
    initLoading.value = true
    const response = await request.post('/menu-permission-mapping/init')
    
    if (response.success) {
      ElMessage.success('初始化完成')
      parseMappingResult(response.data)
    } else {
      ElMessage.error(response.message || '初始化失败')
    }
  } catch (error) {
    console.error('初始化菜单权限映射失败:', error)
    ElMessage.error('初始化失败')
  } finally {
    initLoading.value = false
  }
}

// 解析映射结果
const parseMappingResult = (resultText) => {
  const lines = resultText.split('\n')
  
  // 解析统计信息
  const stats = {}
  lines.forEach(line => {
    if (line.includes('个菜单')) {
      const match = line.match(/(\d+)\s*个菜单/)
      if (match) stats.totalMenus = parseInt(match[1])
    }
    if (line.includes('个权限')) {
      const match = line.match(/(\d+)\s*个权限/)
      if (match) stats.totalPermissions = parseInt(match[1])
    }
    if (line.includes('已映射菜单')) {
      const match = line.match(/已映射菜单：(\d+)/)
      if (match) stats.mappedMenus = parseInt(match[1])
    }
    if (line.includes('未映射菜单')) {
      const match = line.match(/未映射菜单：(\d+)/)
      if (match) stats.unmappedMenus = parseInt(match[1])
    }
  })
  
  statistics.value = stats
  
  // 设置状态
  if (stats.unmappedMenus > 0) {
    mappingStatus.value = {
      title: '菜单权限映射不完整',
      type: 'warning',
      description: `发现 ${stats.unmappedMenus} 个菜单未映射权限，建议执行修复操作`
    }
  } else {
    mappingStatus.value = {
      title: '菜单权限映射完整',
      type: 'success',
      description: '所有菜单都已正确映射权限'
    }
  }
}

// 获取菜单类型标签样式
const getMenuTypeTag = (type) => {
  switch (type) {
    case 'DIRECTORY': return 'warning'
    case 'MENU': return 'success'
    case 'BUTTON': return 'info'
    default: return ''
  }
}

// 获取菜单类型文本
const getMenuTypeText = (type) => {
  switch (type) {
    case 'DIRECTORY': return '目录'
    case 'MENU': return '菜单'
    case 'BUTTON': return '按钮'
    default: return '未知'
  }
}

onMounted(() => {
  checkMapping()
})
</script>

<style scoped>
.menu-permission-binding {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.binding-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.binding-header h3 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 2.5em;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9em;
  opacity: 0.9;
}

.mapping-details h4 {
  margin-bottom: 15px;
  color: #333;
}
</style> 